#include <cstdlib>
#include <iostream>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>

// 对DMS平台的短信通知类与接口进行二次封装: 以便于在项目中使用, 我们每次发送短信的时候, 不希望每次都写很长的代码
// 封装思想: 封装一个DMS客户端类
// 1. 构造时候, 传入访问密钥相关信息
// 2. 向外提供调用接口 (手机号, 验证码) -- 用于向平台发送请求

namespace wufan_im{
class DMSClient{
    public:
        using ptr = std::shared_ptr<DMSClient>;
        DMSClient(const std::string& access_key_id, const std::string& access_key_secret) {
            AlibabaCloud::InitializeSdk();
            AlibabaCloud::ClientConfiguration configuration( "cn-hangzhou" );
            // specify timeout when create client.
            configuration.setConnectTimeout(1500);
            configuration.setReadTimeout(4000);
            AlibabaCloud::Credentials credential(access_key_id, access_key_secret);
            _client = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
        }
        ~DMSClient() {
            AlibabaCloud::ShutdownSdk();
        }
        bool send(const std::string& phone, const std::string& code) {
            AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
            request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setQueryParameter("Action", "SendSms");
            request.setQueryParameter("SignName", "聊天学习系统");      /////////////需要修改这三个地方
            request.setQueryParameter("TemplateCode", "SMS_478490600");/////////////
            request.setQueryParameter("PhoneNumbers", phone);          /////////////
            std::string param_code = "{\"code\":\"" + code + "\"}";
            request.setQueryParameter("TemplateParam", param_code);
            auto response = _client->commonResponse(request);
            if (!response.isSuccess()) {
                printf("error: %s\n", response.error().errorMessage().c_str());
                printf("request id: %s\n", response.error().requestId().c_str());
                return false;
            }
            printf("request success.\n");
            printf("result: %s\n", response.result().payload().c_str());
            return true;
        }
    private:
        std::unique_ptr<AlibabaCloud::CommonClient> _client;
};
}